/**
 * 用户基本信息表
 */
const APIError = require('../middlewares/result.js').APIError;
const ApiErrorNames = require('../config/ApiErrorNames.js');
const { DataTypes } = require('sequelize');
const sequelize = require('../config/sequlieze');

// // sequelize 会自动创建creatAt和updatedAt
const User = sequelize.define(
  'User',
  {
    // id: {
    //   type: DataTypes.NUMBER,
    //   defaultValue: 0,
    //   primaryKey: true,
    //   autoIncrement: true,
    // },
    userId: {  // 当前时间毫秒数+3位随机数
      type: DataTypes.STRING,
      allowNull: false,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    phone: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    unit: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    dept: {
      // 注册的时候使用的
      type: DataTypes.STRING,
      allowNull: false,
    },
    sex: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    code: {
      type: DataTypes.STRING, // 微信获取手机号时的code
      allowNull: false,
    }
  },
  {
    tableName: 'Users',
  }
);

User.sync({ alter: true }); // 检查数据库中表的状态，然后进行必要的更改以使其与模型匹配

//查询所有用户
let findAllUser = async () => {
  let result = User.findAll();
  return result;
};

// 根据用户名查询
let findUserByName = async (name) => {
  let result = await User.findOne({
    where: {
      name,
    },
  }).catch((e) => {
    throw Error(e);
  });
  if (result && result.name === name) {
    const {userId, ...other} = result;
    return {
      ...other
    };
  }
  return null;
};

// 根据userid查询
let findUserById = async (userId) => {
  let result = await User.findOne({
    where: {
      userId,
    },
  });
  if (result.userId === userId) {
    const {userId, id, ...other} = JSON.parse(JSON.stringify(result));
    console.log(userId, id);
    return {
      ...other
    };
  }
  return null;
};

// 根据用户手机号查询
let findUserByPhone = async (phone) => {
  let result = await User.findOne({
    where: {
      phone: phone,
    },
    attributes: [
      'name',
      'unit',
      'dept',
      'sex',
      'userId',
    ]
  });
  if(!result) return null;
  return result;
};

// 通过wx获取手机号时的code获取用户信息
const checkWxCode = async (code, phone) => {
  let result = await User.findOne({
    where: {
      code,
      phone,
    },
    attributes: [
      'name',
      'unit',
      'dept',
      'sex',
      'userId',
    ]
  });
  if(!result) return null;
  return result;
};

// 新增用户
let addUserData = async (value) => {
  let result = await User.create(value);
  return result;
};

// 更新用户信息
const updateUserDataByUserId = async (data) => {
  const { userId, ...other } = data;
  let user = await User.findOne({
    where: {
      userId
    },
  });
  if(user) {
    await user.update({
      ...other
    });
    const {userId, name, unit, dept, sex} = user;
    return {
      userId,
      name,
      unit,
      dept,
      sex,
    };
  } else {
    throw new APIError(ApiErrorNames.PARAMS_ERR);
  }
};

module.exports = {
  User,
  findUserByName,
  addUserData,
  findAllUser,
  findUserById,
  findUserByPhone,
  checkWxCode,
  updateUserDataByUserId,
};
